import email
import json
import time

import requests
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import HttpResponseRedirect, JsonResponse
from .models import *
from .serilizers import *

from django.contrib.auth.hashers import check_password
from tools.myjwt import mjwt

from tools.aliyun import aliyun


# Create your views here.

def loginsuccess(user: Tusers):
    payload = {"username": user.name, "exp": int(time.time()) + 60 * 60 * 2}
    token = mjwt.jwt_encode(payload)
    payload["exp"] = int(time.time() + 60 * 60 * 24 * 2)
    refreshToken = mjwt.jwt_encode(payload)
    return Response({
        "code": 200,
        "username": user.name,
        'token': token,
        "refreshToken": refreshToken
    })


class Login(APIView):
    def post(self, request):
        # 获取用户名和密码
        mobile = request.data.get('mobile')
        password = request.data.get('password')
        # 查询用户表
        # 如果存在密码对比
        user = Tusers.objects.filter(mobile=mobile).first()
        if not user:
            return Response({"code": 11001, "msg": "用户未注册，请先注册"})
        # if not check_password(password, user.password):
        #     return Response({"code": 11002, "msg": "密码错误"})
        if password != user.passwd:
            return Response({"code": 11002, "msg": "密码错误"})

        # 如果正确调用 jwt生成token
        payload = {"userid": user.id, "username": user.name, "exp": int(time.time()) + 60 * 60 * 2}
        token = mjwt.jwt_encode(payload)

        return Response({
            "code": 200,
            'user': {"token": token, 'id': user.id, 'account': user.name,
                     'mobile': user.mobile, 'avatar': '', 'uid': user.id}
        })


class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = Tusers.objects.filter(username=username).first()
        if not user:
            return Response({"code": 11001, "msg": "用户未注册，请先注册"})
        if not check_password(password, user.password):
            return Response({"code": 11002, "msg": "密码错误"})
        return loginsuccess(user)


# def loginsuccess(user: Tusers):
#     payload = {"user_id": user.id, "username": user.username, "exp": int(time.time()) + 60 * 60 * 2}
#     token = myjwt.jwt_encode(payload)
#     payload['exp'] = int(time.time()) + 60 * 60 * 24 * 2
#     refreshToken = myjwt.jwt_encode(payload)
#     return Response({"code": 10000,
#                      "message": '登录成功',
#                      "data": {
#                          "account": user.username,
#                          "avatar": user.pic_url,
#                          'id': user.id,
#                          "mobile": user.mobile[:4] + "****" + user.mobile[-5:],
#                          "refreshToken": refreshToken,
#                          "token": token
#                      }
#                      })


class Login_data(APIView):

    def get(self, request):
        # 查询出来所有的数据
        data = Tusers.objects.all()
        # 应该用循环取出数据
        print(data)
        return Response({'code': '10010'})

    def post(self, request):
        # 获取目录路径
        path = request.path
        # print(path)
        # 使用get获取数据的信息
        username = request.data.get('mobile')
        password = request.data.get('passwd', None)
        # 验证码,
        code = request.data.get('code', None)
        # print(request.data)
        # 没有密码的时候验证code数据
        if not password:
            code_data = r.str_get(username)
            print(code_data)
            if code == code_data:
                user = Tusers.objects.filter(mobile=username).first()
                if not user:
                    return Response({"code": 11001, "msg": "用户未注册，请先注册"},status=status.HTTP_403_FORBIDDEN)
                return loginsuccess(user)
            return Response({"code": 11001, "msg": "验证码错误!!!"},status=status.HTTP_403_FORBIDDEN)
        # 密码登录
        user = Tusers.objects.filter(name=username).first()
        if not user:
            return Response({"code": 11001, "msg": "用户未注册，请先注册"},status=status.HTTP_403_FORBIDDEN)
        # print(user)
        # 使用django自带的数据自动转换数据将登录信息和数据库的的加密信息验证
        if not check_password(password, user.passwd):
            # 这个是数据的返回
            return Response({"code": 11002, "msg": "密码错误"})
        return loginsuccess(user)


class RefreshTokenVIew(APIView):
    def post(self, request):
        refreshToken = request.data.get('refreshToken')
        payload = mjwt.jwt_decode(refreshToken)
        if int(time.time()) <= payload["exp"]:
            now = int(time.time())
            payload["exp"] = now + 60 * 60 * 2
            token = mjwt.jwt_encode(payload)
            payload["exp"] = now + 60 * 60 * 24 * 2
            retoken = mjwt.jwt_encode(payload)
            return JsonResponse({"code": 200, "token": token, "refreshToken": retoken})
        else:
            return JsonResponse({"code": 401, "msg": "登录已过期，请重新登录"})


class RegisterView(APIView):
    def post(self, request):
        # 假设你有一个序列化器来处理 Tusers 模型
        serializer = TusersSerializer(data=request.data)

        if serializer.is_valid():
            # 保存用户
            user = serializer.save()
            # 序列化用户对象
            user_data = TusersSerializer(user).data
            return Response(user_data, status=status.HTTP_201_CREATED)
        else:
            # 返回验证错误
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


from tools.mredis import r
import random


# 发送短信验证码
class SendSms(APIView):

    def get(self, requests):
        # 1.获取手机号
        mobile = requests.GET.get('mobile')
        # 2.查询手机号发送的次数，如果大于等于3次，提示不能再发
        code = r.str_get(mobile)
        if code:
            return Response({'code': 10010, 'mes': '已经发过不能再发'})
        # 3.调用阿里云短信接口发送
        smscode = random.randint(10000, 99999)

        # 4.把验证码存入redis
        r.str_setex(mobile, smscode, 60)
        return Response({'code': 200, 'mes': '发送成功'})


# 5.用户在页面，输入验证码，点击登录
class MobileLogin(APIView):

    def post(self, request):

        # 获取手机号和用户输入的验证码
        mobile = request.data.get('mobile')
        inputcode = request.data.get('code')

        # 通过手机号去redis中查询验证码和用户输入的是否一致
        code = r.str_get(mobile)
        if code:
            if int(code) == int(inputcode):
                # 如果一致，获取用户信息
                user = Tusers.objects.filter(mobile=mobile).first()
                if not user:
                    return Response({'code': 11001, 'msg': '用户未注册，请先注册'})

                # 如果正确调用，jwt生成token
                payload = {'userid': user.id, 'username': user.name, 'exp': int(time.time())+60*60*2}
                token = mjwt.jwt_encode(payload)

                return Response({
                    "code": 200,
                    'user': {"token": token, 'id': user.id, 'account': user.name,
                             'mobile': user.mobile, 'avatar': '', 'uid': user.id}
                })

        return Response({'code': 10010, 'mes': '验证码不正确'})


class Code(APIView):

    def get(self, request):

        phone = request.GET.get('mobile')
        # type = request.GET.get('type')
        code = random.randint(100000, 999999)
        code_dict = {'code': code}
        r.str_add(phone, code)
        aliyun.sms(mobile=phone, template_param=code_dict,)
        return Response(code_dict)


class DingTalkLogin(APIView):
    def get(self, request):
        from urllib.parse import quote
        params = [
            f"redirect_uri={quote('http://127.0.0.1:8000/ddcallback/')}",
            "response_type=code",
            "client_id=ding35hiwyxbdbywwuv0",
            "scope=openid",
            "prompt=consent"
        ]
        url = "https://login.dingtalk.com/oauth2/auth?" + ("&".join(params))
        return Response({"url": url})


from django.http import HttpResponseRedirect


class DingdingCallback(APIView):
    def get(self, request):
        authCode = request.query_params.get('code')

        # 根据authCode获取用户accessToken
        data = {
            "clientId": "ding35hiwyxbdbywwuv0",
            "clientSecret": "muv_6nLtagN6C_6U-nwvki_xVn_DZKEAhyTxv1br34T3pdwK4BIeXd_zrSCheEU7",
            "code": authCode,
            "grantType": "authorization_code"
        }
        # 获取token授权
        resp = requests.post('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', json=data).json()
        accessToken = resp.get('accessToken')

        # 根据accessToken获取用户信息
        headers = {"x-acs-dingtalk-access-token": accessToken}
        resp = requests.get('https://api.dingtalk.com/v1.0/contact/users/me', headers=headers).json()
        name = resp.get('nick')
        uid = resp.get('openId')
        phone = resp.get('mobile')

        # 根据uid查询三方登录表，如果存在,
        sfuser = SFLogin.objects.filter(uid=uid).first()
        if sfuser:
            userid = sfuser.userid.id
            username = sfuser.userid.name
        else:
            # 写入用户表，写入三方登录表
            users = Tusers.objects.create(name=phone, passwd='123', mobile=phone, email='234', pic_url='1.jpg')
            SFLogin.objects.create(userid=users, l_type='dingding', uid=uid)

            userid = users.id
            username = name

        payload = {"userid": userid, "username": username, "exp": int(time.time()) + 7200}
        token = mjwt.jwt_encode(payload)

        return HttpResponseRedirect('http://localhost:80/updatetoken?token=' + token + "&userid=" + username)


class DepartmentView(APIView):
    def get(self,request):
        dep = Department.objects.filter(pid__isnull=True).all()
        ser = DepartmentSer(dep,many=True)
        return Response({"code":10000,'data':ser.data})


from qiniu import Auth
class GetQnToken(APIView):
    def get(self, request):
        # 需要填写你的 Access Key 和 Secret Key
        # 七牛云：
        # AccessKey：
        # OWOlE34ihI19PqOgewyOwgtMmiuHOVRrYAhHs8oI
        # SecretKey：
        # gvnzdP1x6hQkzquncadJN587KC5SDRwz2ahUTEte
        access_key = 'OWOlE34ihI19PqOgewyOwgtMmiuHOVRrYAhHs8oI'
        secret_key = 'gvnzdP1x6hQkzquncadJN587KC5SDRwz2ahUTEte'
        # 构建鉴权对象
        q = Auth(access_key, secret_key)
        # 要上传的空间
        bucket_name = '2309a'

        # 3600为token过期时间，秒为单位。3600等于一小时
        token = q.upload_token(bucket_name)
        return Response({"code": 10000, 'data': token})


# class GetQnToken(APIView):
#     def get(self,request):
#         return Response({"code":10000,'data':'asdfsdfsdfsd'})


class PatientView(APIView):
    def get(self, request):
        userid = request.GET.get('userid', 1)
        id = request.GET.get('id')
        if id:
            # 获取单个患者
            patient = Patient.objects.filter(id=id).first()
            ser = PatientSer(patient)
            return Response({"code": 10000, 'data': ser.data})
        patient = Patient.objects.filter(userid_id=userid).all()
        ser = PatientSer(patient, many=True)
        return Response({"code": 10000, 'data': ser.data})

    # 添加患者
    # def post(self, request):
    #     # 从请求体中获取患者数据
    #     serializer = PatientSer(data=request.data)
    #
    #     if serializer.is_valid():
    #         # 保存患者信息
    #         serializer.save()
    #         # 返回创建的患者信息
    #         return Response({"code":10000,"data":serializer.data}, status=status.HTTP_201_CREATED)
    #     else:
    #         # 如果数据无效，返回错误信息
    #         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class PatientaddView(APIView):
    def post(self, request):
        idCard = request.data.get('idCard')
        print(idCard)
        if idCard:
            patient = Patient.objects.filter(code=idCard).first()
            if patient:
                return Response({"code": 10000, 'data': '该患者已存在'})
            else:
                defaultFlag = request.data.get('defaultFlag')
                print(defaultFlag)
                if defaultFlag:
                    userid = request.GET.get('userid', 1)
                    patient = Patient.objects.filter(userid_id=userid).all()
                    for i in patient:
                        i.is_default = False
                        i.save()
                Patient.objects.create(code=idCard, name=request.data.get('name'), sex=request.data.get('gender'),
                                       is_default=request.data.get('defaultFlag'), userid_id=request.data.get('userid'))

                return Response({"code": 10000, 'data': '添加成功'})

        return Response({"code": 10000, 'data': '添加失败'})


#获取此订单可用的优惠卷，订单金额
class Preorder(APIView):
    def get(self,request):
        #获取参数，两个类型type=2&illnessType=1
        type = request.GET.get('type')
        illnessType = request.GET.get('illnessType')
        #查询积分，积分记录表，用户表中的总积分数
        tuser = Tusers.objects.filter(id=5).first()
        #携带userid，根据userid查询总积分
        pointDeduction = tuser.tscore

        # 优惠券，
        usercoupon = UserCoupon.objects.filter(userid_id=5).first()
        couponDeduction = usercoupon.money
        couponId = 1

        # 支付费用
        fee = Fee.objects.filter(types=type,docker_types=illnessType).first()
        if fee.money > pointDeduction:
            payment = fee.money - pointDeduction
            if payment > couponDeduction:
                payment = payment - couponDeduction

        #根据用户id查询用户优惠券表
        dict = {"pointDeduction":pointDeduction,'couponDeduction':couponDeduction,"couponId":couponId,'payment':payment,'actualPayment':payment}
        return Response({"code":10000,'data':dict})


#   /** 积分抵扣 */
#   pointDeduction: number
#   /** 优惠券抵扣 */
#   couponDeduction: number
#   /** 优惠券ID */
#   couponId: string
#   /** 需付款 */
#   payment: number
#   /** 实付款 */
#   actualPayment: number

import random, time
from tools.myredis import r


class OrdersView(APIView):
    def post(self, request):
        # 获取数据
        data = request.data
        print(data)
        # 接口幂等性判断
        key = data['orderkey']
        # mes = r.str_get(key)
        # if not mes:
        #     return Response({"code":400,'message':'不能重复生成订单'})
        # r.key_del(key)
        # 从token中获取
        userid = 5
        # {'type': 2, 'illnessType': 1, 'depId': 5,  'couponId': 1}
        score = Score.objects.filter(userid_id=5).first()
        couponmoney = 0
        tmoney = 0
        pay_money = 0
        # 根据优惠卷couponId查询优惠金额
        if data['couponId'] > 0:
            coupon = Coupon.objects.filter(id=data['couponId']).first()
            couponmoney = coupon.money

        # 查询订单金额
        # 支付费用
        fee = Fee.objects.filter(types=data['type'], docker_types=data['illnessType']).first()
        tmoney = fee.money

        # 查询可用的积分
        users = Tusers.objects.filter(id=userid).first()
        userscore = users.tscore
        # 判断订单的支付金额，
        p_money = tmoney - couponmoney
        # 付的钱多于积分
        if p_money > userscore:
            score = userscore
        elif p_money < userscore:
            score = p_money
        # 支付金额
        pay_money = tmoney - couponmoney - score
        # 生成订单号
        orderno = str(int(time.time())) + str(userid) + str(random.randint(10000, 99999))
        orderdict = {'orderno': orderno, "descrip": data['illnessDesc'], 'times': data['illnessTime'],
                     'pic_url': json.dumps(data['pictures']), 'is_into': data['consultFlag'],
                     'patient': data['patientId'], 'userid': userid, 'status': 1,
                     'transaction': '0', 'pay_type': 1, 'docker_types': data['illnessType'],
                     'types': data['type'], 'department': data['depId'], 'score': score,
                     'couponid': data['couponId'], 'couponmoney': couponmoney, 'tmoney': tmoney, 'pay_money': pay_money}
        # 写入订单表
        ser = OrdersSer(data=orderdict)
        if ser.is_valid():
            ser.save()
            return Response({"code": 10000, 'data': {"id": orderno}})
        print(ser.errors)
        # 记录积分使用情况，优惠卷
        return Response({"code": 400})


import uuid


class OrdersKey(APIView):
    def get(self, request):
        # 获取userid
        # userid = request.GET.get('userid')
        # 生成唯一标识
        key = uuid.uuid1().hex
        # 将key存入redis
        r.str_set(key,key)
        # 返回
        return Response({"code": 10000, 'data': {"key": key}})


from tools.bdapi import bdapi
class IdcodeView(APIView):
    def get(self,request):
        #获取图片地址
        url = request.GET.get('picurl')
        print(url)
        #调用bdapi识别
        data = bdapi.fontmessage(url)
        #返回结果
        return Response({"code":200,'usermes':data})


from tools.comm import get_alipay
# 事务处理
from django.db import transaction



# 获取支付宝链接
# class PayView(APIView):
#     def post(self, request):
#         payUrl = ''
#         pay_money = 0
#         # 获取参数  订单号和支付方式
#         orderno = request.data['orderId']
#         paymentMethod = request.data['paymentMethod']
#         # 根据订单号查询订单实付金额
#         orders = Orders.objects.filter(orderno=orderno).first()
#         if orders:
#             pay_money = orders.pay_money
#         else:
#             return Response({"code": 10010, 'message': '订单不存在，不能支付'})
#         # 调用支付宝封装支付链接
#         if paymentMethod == 1:
#             pay = get_alipay()
#             query_params = pay.direct_pay(
#                 subject="问诊支付",  # 商品简单描述
#                 out_trade_no=str(orderno),  # 用户购买的商品订单号（每次不一样） 20180301073422891
#                 total_amount=float(pay_money),  # 交易金额(单位: 元 保留俩位小数)
#             )
#             payUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do?{0}".format(query_params)
#         else:
#             # 封装调用微信链接
#             paymentMethod = 2
#
#         # 更新订单表中支付方式
#         orders.pay_type = paymentMethod
#         orders.save()
#         # 返回链接
#         return Response({"code": 10000, 'data': {"payUrl": payUrl}})
#
#     # 回调后的处理
#     @transaction.atomic()
#     def get(self, request):
#         # 获取参数
#         # 验证签名
#         mes = request.GET
#         # 对参数进行处理
#         data = {k: v for k, v in mes.items()}
#         # 验证签名
#         pay = get_alipay()
#         sign = data.pop('sign')
#         flag = pay.verify(data, sign)
#         # 判断是否通过，如果通过
#         if flag:
#             # 获取订单号
#             # 支付宝流水号
#             transaction_no = data['trade_no']
#             # 订单号
#             order_no = data['out_trade_no']
#             sid = transaction.savepoint()
#             try:
#                 # 2.更新订单表为已支付状态
#                 orders = Orders.objects.filter(orderno=order_no).first()
#                 if orders:
#                     orders.status = 2
#                     orders.transaction = transaction_no
#                     orders.save()
#                 # 3.判断是否使用积分，更新积分记录表，用户表中总积分减少
#                 if orders.score > 0:
#                     Score.objects.create(userid=orders.userid, l_type=2, score=orders.score)
#                     tusers = Tusers.objects.filter(id=orders.userid).first()
#                     tusers.tscore -= int(orders.score)
#                     tusers.save()
#                 # 4.是否使用优惠卷，更新用户优惠卷表中的使用状态
#                 if orders.couponid > 0:
#                     UserCoupon.objects.filter(id=orders.couponid).update(status=2)
#                 transaction.savepoint_commit(sid)
#                 # 将订单号加入队列
#                 r.list_add('doctorlist', order_no)
#                 return HttpResponseRedirect('http://localhost/room/')
#             except:
#                 transaction.savepoint_rollback(sid)
#
#         return HttpResponseRedirect('http://localhost/pay_error')


# class PayView(APIView):
#     def post(self, request):
#         payUrl = ''
#         pay_money = 0
#         # 获取参数  订单号和支付方式
#         orderno = request.data['orderId']
#         paymentMethod = request.data['paymentMethod']
#         # 根据订单号查询订单实付金额
#         orders = Orders.objects.filter(orderno=orderno).first()
#         if orders:
#             pay_money = orders.pay_money
#         else:
#             return Response({"code": 10010, 'message': '订单不存在，不能支付'})
#         # 调用支付宝封装支付链接
#         if paymentMethod == 1:
#             pay = get_alipay()
#             query_params = pay.direct_pay(
#                 subject="问诊支付",  # 商品简单描述
#                 out_trade_no=str(orderno),  # 用户购买的商品订单号（每次不一样） 20180301073422891
#                 total_amount=float(pay_money),  # 交易金额(单位: 元 保留俩位小数)
#             )
#             payUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do?{0}".format(query_params)
#         else:
#             # 封装调用微信链接
#             paymentMethod = 2
#
#         # 更新订单表中支付方式
#         orders.pay_type = paymentMethod
#         orders.save()
#         # 返回链接
#         return Response({"code": 10000, 'data': {"payUrl": payUrl}})
#
#     # 回调后的处理
#     @transaction.atomic()
#     def get(self, request):
#         # 获取参数
#         # 验证签名
#         mes = request.GET
#         # 对参数进行处理
#         data = {k: v for k, v in mes.items()}
#         print(data)
#         # 验证签名
#         pay = get_alipay()
#         sign = data.pop('sign')
#         flag = pay.verify(data, sign)
#
#         # 判断是否通过，如果通过
#         if flag:
#             # 获取订单号
#             # 支付宝流水号
#             transaction_no = data['trade_no']
#             # 订单号
#             order_no = data['out_trade_no']
#             sid = transaction.savepoint()
#             # 查询订单状态
#             query_params = pay.query_pay(out_trade_no=str(order_no))
#             payUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do?{0}".format(query_params)
#             res = json.loads(requests.get(payUrl).text)
#             print(res)
#
#             if res['alipay_trade_query_response']['code'] == "10000":
#                 # 查询订单状态，如果支付成功，更新订单状态，把订单号写入队列中
#                 # Orders.objects.filter(orderno=order_no).update(status=2, transaction=transaction_no)
#                 # r.list_push('setdockersuccess', order_no)
#                 orders = Orders.objects.filter(orderno=order_no).first()
#                 if orders:
#                     orders.status = 2
#                     orders.transaction = transaction_no
#                     orders.save()
#
#                 # 3.判断是否使用积分，更新积分记录表，用户表中总积分减少
#                 if orders.score > 0:
#                     Score.objects.create(userid=orders.userid, l_type=2, score=orders.score)
#                     tusers = Tusers.objects.filter(id=orders.userid_id).first()
#                     tusers.tscore -= int(orders.score)
#                     tusers.save()
#                 # 4.是否使用优惠卷，更新用户优惠卷表中的使用状态
#                 if orders.couponid > 0:
#                     UserCoupon.objects.filter(id=orders.couponid).update(status=2)
#                 transaction.savepoint_commit(sid)
#                 r.list_push('setdockersuccess', order_no)
#                 return HttpResponseRedirect('http://localhost/room/')
#             else:
#                 Orders.objects.filter(orderno=order_no).update(status=3, transaction=transaction_no)
#                 r.list_push('setdockerfail', order_no)
#                 return HttpResponseRedirect('http://127.0.0.1:8000/fail')


class PayView(APIView):
    def post(self, request):
        payUrl = ''
        pay_money = 0
        # 获取参数  订单号和支付方式
        orderno = request.data['orderId']
        paymentMethod = request.data['paymentMethod']
        # 根据订单号查询订单实付金额
        orders = Orders.objects.filter(orderno=orderno).first()
        if orders:
            pay_money = orders.pay_money
        else:
            return Response({"code": 10010, 'message': '订单不存在，不能支付'})
        # 调用支付宝封装支付链接
        if paymentMethod == 1:
            pay = get_alipay()
            query_params = pay.direct_pay(
                subject="问诊支付",  # 商品简单描述
                out_trade_no=str(orderno),  # 用户购买的商品订单号（每次不一样） 20180301073422891
                total_amount=float(pay_money),  # 交易金额(单位: 元 保留俩位小数)
            )
            payUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do?{0}".format(query_params)
        else:
            # 封装调用微信链接
            paymentMethod = 2

        # 更新订单表中支付方式
        orders.pay_type = paymentMethod
        orders.save()
        # 返回链接
        return Response({"code": 10000, 'data': {"payUrl": payUrl}})

    @transaction.atomic()
    def get(self, request):
        # 获取参数
        # 验证签名
        mes = request.GET
        # 对参数进行处理
        data = {k: v for k, v in mes.items()}
        print(data)
        # 验证签名
        pay = get_alipay()
        sign = data.pop('sign')
        flag = pay.verify(data, sign)

        # 判断是否通过，如果通过
        if flag:
            # 获取订单号
            # 支付宝流水号
            transaction_no = data['trade_no']
            # 订单号
            order_no = data['out_trade_no']
            # 查询订单状态
            query_params = pay.query_pay(out_trade_no=str(order_no))
            payUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do?{0}".format(query_params)
            mes = requests.get(payUrl)
            res = json.loads(mes.text)
            print(res)

            if res['alipay_trade_query_response']['code'] == "10000":
                # 查询订单状态，如果支付成功，更新订单状态，把订单号写入队列中
                Orders.objects.filter(orderno=order_no).update(status=2, transaction=transaction_no)
                r.list_push('setdockersuccess', order_no)
                return HttpResponseRedirect('http://localhost:8000/success')
            else:
                Orders.objects.filter(orderno=order_no).update(status=3, transaction=transaction_no)
                r.list_push('setdockerfail', order_no)
                return HttpResponseRedirect('http://localhost:8000/fail')


class OrderSuccess(APIView):
    def get(self, request):
        slist = r.list_all('setdockersuccess')
        for s in slist:
            orderno = s.decode()
            # 分配医生
            orders = Orders.objects.filter(orderno=orderno).first()
            deptid = orders.department_id
            print(deptid)
            # 去医生表中查询医生
            dockers = Doctor.objects.filter(deptid_id=deptid).all()
            # 获取所有医生的id
            idslist = [i.id for i in dockers]
            count = len(idslist)
            print(count)
            value = hash(orderno) % count
            setdockerid = idslist[value]
            PatientDoctor.objects.create(userid_id=orders.userid_id, doctorid_id=setdockerid,
                                         patient_id=orders.patient_id, orderno=orderno)

            # orders.dockerid = setdockerid
            # orders.save()

        return HttpResponseRedirect('http://localhost/room/')


class OrderFail(APIView):
    def get(self, request):
        slist = r.list_all('setdockerfail')
        for s in slist:
            orderno = s.decode()
            # 恢复
            orders = Orders.objects.filter(orderno=orderno).first()
            # 根据优惠卷couponId查询优惠金额
            if orders.couponid > 0:
                UserCoupon.objects.filter(id=orders.couponid).update(status=1)

            if orders.score > 0:
                # ScoreRecord.objects.create()
                users = Tusers.objects.filter(id=id).first()
                users.tscore += orders.score
                users.save()
            r.list_del('setdockerfail',orderno)
        return Response({'code': '200'})

# 支付宝付款测试
class PayTest(APIView):
    def post(self,reqeust):
        #获取订单号
        orderno = "324t454"
        #根据订单号查询金额
        pay_money = 30
        #获取支付的url
        pay = get_alipay()
        query_params = pay.direct_pay(
            subject="问诊支付",  # 商品简单描述
            out_trade_no=str(orderno),  # 用户购买的商品订单号（每次不一样） 20180301073422891
            total_amount=float(pay_money),  # 交易金额(单位: 元 保留俩位小数)
        )
        payUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do?{0}".format(query_params)
        return Response({"code":200,'url':payUrl})


class PatientDoct(APIView):
    def get(self,request):
        doct = 3
        patien = PatientDoctor.objects.filter(doctorid_id=doct).all()
        pat = PatientDoctorList(patien,many=True)
        data = [i['patient'] for i in pat.data]
        patlist = []
        for j in data:
            li = Patient.objects.filter(id=j).all()
            list = PatientSer(li,many=True)
            ll = {"id":list.data[0]['id'],"name":list.data[0]['name']}
            patlist.append(ll)
        print(patlist)
        return Response({"code": 200, 'list':patlist})
